package com.example.bbs.aspect;


import com.alibaba.fastjson.JSON;
import com.example.bbs.aspect.annotation.OperationLog;
import com.example.bbs.domain.model.WebLog;
import com.example.bbs.util.HostHold;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 接口日志记录
 */
@Component
@Aspect
@Slf4j
public class WebLogAspect {

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.example.bbs.controller.*.*(..))")
    public void pointcut() {};

    @Around("pointcut() && @annotation(operationLog)")
    public Object Around(ProceedingJoinPoint proceedingJoinPoint, OperationLog operationLog) throws Throwable {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            log.error("doAround error: 当前请求对象为null, attributes is null");
            return null;
        }
        HttpServletRequest request = attributes.getRequest();
        Object result = proceedingJoinPoint.proceed();

        WebLog webLog = new WebLog();
        webLog.setLoginUserId(HostHold.get() == null ? null : HostHold.get().getUserId());
        webLog.setDescription(operationLog.value());
        webLog.setIp(request.getRemoteAddr());
        webLog.setMethod(request.getMethod());
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setParam(JSON.toJSONString(request.getParameterMap()));
        webLog.setResult(result.toString());

        log.info(webLog.toString());
        return result;
    }
}